package com.doget.data.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.Toast;

import com.doget.data.R;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.InputStream;
import java.util.List;

import io.reactivex.functions.Consumer;

//import com.baidu.mobstat.StatService;

public class LaunchActivity extends BaseActivity implements View.OnClickListener,
        VersionPresenter.View, LaunchPresenter.View {

    VersionPresenter m_versionPresenter;
    LaunchPresenter launchPresenter;
    private ImageView layoutSplash;
    private boolean isShowedUpdate;
    private String deviceId;

    //private static Boolean checkv = true;
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            llyBottom.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "横屏", Toast.LENGTH_SHORT).show();
        } else {
//            llyBottom.setVisibility(View.VISIBLE);
            Toast.makeText(getApplicationContext(), "竖屏", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCreateView(Bundle bundle) {
        setContentView(R.layout.activity_launch);


        m_versionPresenter = new VersionPresenter();

        launchPresenter = new LaunchPresenter();
        launchPresenter.getDynamicUrl();
        setDeviceId();
    }

    private AlphaAnimation alphaAnimation;

    @Override
    protected void initView() {
        layoutSplash = (ImageView) findViewById(R.id.activity_splash);
        showAnim();
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onResume() {
        super.onResume();
    }

    @SuppressLint("CheckResult")
    private void requestPermission() {
        layoutSplash.setVisibility(View.VISIBLE);
        try {
            final RxPermissions rxPermissions = new RxPermissions(this);
            rxPermissions
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO,
                            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)

                    .subscribe(new Consumer<Boolean>() {

                                   @Override
                                   public void accept(Boolean o) throws Exception {
                                   }
                    });
//                    .subscribe(granted -> {
////                        if (granted) { // Always true pre-M
//////                            m_versionPresenter.getAppVersion(String.valueOf(System.currentTimeMillis()));
////                        } else {
////                            ToastUtil.show("请先授予相关权限");
////                            finish();
////                        }
//                    });
        } catch (Exception e) {
            e.printStackTrace();
            m_versionPresenter.getAppVersion(String.valueOf(System.currentTimeMillis()));
        }
    }

    //设置动画监听
    private void showAnim() {

        try {
//            getBitmapForImgResourse(this, R.drawable.bitmap_splash_center, layoutSplash);
        } catch (Exception e) {
//            layoutSplash.setImageResource(R.drawable.bitmap_splash_center);
        }

        alphaAnimation = new AlphaAnimation(0.1f, 1.0f);
        alphaAnimation.setDuration(1000);//设置动画播放时长1000毫秒（1秒）
        layoutSplash.startAnimation(alphaAnimation);
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            //动画结束
            @Override
            public void onAnimationEnd(Animation animation) {
                requestPermission();
                //隐私政策弹窗
//                boolean hasShownPrivacyProtocol = SPUtil.getInstance().getBooleanValue(Consts.SPKeys.HasShownPrivacyProtocol);
//                if (!hasShownPrivacyProtocol) {
//                    try {
//                        getBitmapForImgResourse(LaunchActivity.this, R.drawable.bitmap_splash_center, layoutSplash);
//                    } catch (Exception e) {
//                        layoutSplash.setImageResource(R.drawable.bitmap_splash_center);
//                    }
//                    layoutSplash.setVisibility(View.VISIBLE);
//                    PrivacyProtocolDialog.showLoading(LaunchActivity.this, "file:///android_asset/html/privacy_protocol_simple.html",
//                            new PrivacyProtocolDialog.CustomConfirmInterface() {
//
//                                @Override
//                                public void refuseButtonClick() {
//                                    LaunchActivity.this.finish();
//                                }
//
//                                @Override
//                                public void confirmSureButtonClick() {
//                                    // 通过该接口可以控制隐私权限策略的数据采集，true表示可以采集，false表示不可以采集，请在Application里优先调用
//                                    // 建议有用户隐私策略弹窗的App，用户未同意前设置false,同意之后设置true
//                                    //StatService.setAuthorizedState(LaunchActivity.this, true);
//                                    SPUtil.getInstance().setBooleanValue(Consts.SPKeys.HasShownPrivacyProtocol, true);
//                                    requestPermission();
//                                }
//                            });
//                } else {
//
//                }
            }
            // }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    private void goToMain() {

    }

    @Override
    protected void initData(Bundle bundle) {

    }


    @Override
    protected void initHeader() {

    }

    @Override
    public void onVersionSuccess(VersionResp versionResp) {

    }

    @Override
    public void onVersionFailed(String message) {
        goToMain();
    }

    @Override
    public void onRefreshToken(RefreshTokenBean result) {

    }

    @Override
    public void onDynamicUrlSuccess(DynamicUrlBean bean) {
        if (bean == null) {
            return;
        }
        List<DynamicUrlBean.ValueBean> valueBean = bean.getValue();

    }

    @Override
    public void onDynamicUrlFailed(String message) {
        Log.d("ck--", "获取动态链接失败~");
    }

    @Override
    public void onClick(View view) {

    }

    /**
     * 大图片处理机制
     * 利用Bitmap 转存 R图片
     */
    public static Bitmap btp;
    private ImageView mMImageView;//滑动的动态大图片

    public void getBitmapForImgResourse(Context mContext, int imgId, ImageView mImageView) {
        try {
            mMImageView = mImageView;
            InputStream is = mContext.getResources().openRawResource(imgId);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inPurgeable = true;
            options.inInputShareable = true;
            options.inSampleSize = 1;
            btp = BitmapFactory.decodeStream(is, null, options);
            if (btp != null && mImageView != null) {//防止使用的时候,该图片已经被回收了.
                mImageView.setImageBitmap(btp);
            }
            is.close();
        } catch (Exception e) {
            Log.e("ck--", "E------" + e.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (btp != null) {
            btp.recycle();
            btp = null;
        }
        if (mMImageView != null) {
            try {
                mMImageView.setBackground(null);
            } catch (Exception e) {
                Log.e("ck--", "E----" + e.getMessage());
            }

        }
        System.gc();
    }

    private void setDeviceId() {
        m_versionPresenter.setDeviceId(deviceId);
    }
}
